package com.sky.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.ShoppingCarMapper;
import com.sky.result.Result;
import com.sky.service.IDishService;
import com.sky.service.ISetmealService;
import com.sky.service.IShoppingCarService;
import com.sky.utils.UserThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
 * @BelongsProject: sky-take-out
 * @Author: XieMingHui
 * @CreateTime: 2023-11-27  18:18
 * @Description: 购物车数据处理层实现类
 * @Version: 1.0
 */
@Slf4j
@Service
public class IShoppingCarServiceImpl extends ServiceImpl<ShoppingCarMapper, ShoppingCart> implements IShoppingCarService {
    @Resource
    private IDishService iDishService;
    @Resource
    private ISetmealService iSetmealService;

    /**
     * 添加商品到购物车
     *
     * @author: XieMingHui
     * @param: [shoppingCartDTO]
     * @return: com.sky.result.Result<java.lang.String>
     **/
    @Override
    public Result<String> addCar(ShoppingCartDTO shoppingCartDTO) {
        Long id = UserThreadUtil.getThread().getId();
        log.info("当前用户id:{}", id);
        // 获取菜品id和套餐id
        Long dishId = shoppingCartDTO.getDishId();
        Long setmealId = shoppingCartDTO.getSetmealId();
        // 构建条件
        LambdaQueryChainWrapper<ShoppingCart> wrapper = lambdaQuery().eq(dishId != null, ShoppingCart::getDishId, dishId)
                .eq(setmealId != null, ShoppingCart::getSetmealId, setmealId)
                .eq(ShoppingCart::getUserId, id);
        // 判断该菜品或者套餐是否是首次添加
        Integer count = wrapper.count();
        if (count>0){
            log.info("统计次数为:{},不是首次添加,直接修改对应菜品id或者套餐id的数量+1",count);
            // 更新购物车
            boolean update = isUpdate(id, dishId, setmealId);
            if (update){
                return Result.success("添加成功");
            }else {
                return Result.success("添加失败");
            }
        }else {
            log.info("统计次数为:{},是首次添加",count);
            // 首次添加
            // 封装菜品id或者套餐id和口味到购物车对象
            boolean result = getStringResult(shoppingCartDTO, id, dishId, setmealId);
            if(result){
                return Result.success("添加成功");
            }
            return Result.success("添加失败");
        }
    }
    // 更新购物车
    private boolean isUpdate(Long id, Long dishId, Long setmealId) {
        UpdateWrapper<ShoppingCart> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().setSql("number = number + 1")
                .eq(dishId != null, ShoppingCart::getDishId, dishId)
                .eq(setmealId != null, ShoppingCart::getSetmealId, setmealId)
                .eq(ShoppingCart::getUserId, id);
        return update(updateWrapper);
    }

    // 封装菜品id或者套餐id和口味到购物车对象
    private boolean getStringResult(ShoppingCartDTO shoppingCartDTO, Long id, Long dishId, Long setmealId) {
        ShoppingCart shoppingCartNew = BeanUtil.toBean(shoppingCartDTO, ShoppingCart.class);
        if (dishId != null) {
            log.info("添加菜品到购物车");
            Dish dish = iDishService.getById(dishId);
            // 封装菜品属性
            addDishToCar(shoppingCartNew, id, dish.getName(),dish.getImage(),dish.getPrice());
            // 添加到购物车表
            return save(shoppingCartNew);
        } else {
            log.info("添加套餐到购物车");
            Setmeal setmeal = iSetmealService.getById(setmealId);
            // 封装套餐属性
            addDishToCar(shoppingCartNew, id, setmeal.getName(),setmeal.getImage(),setmeal.getPrice());
            // 添加到购物车表
            return save(shoppingCartNew);
        }
    }

    /**
     * 封装属性到购物车对象
     * @author: XieMingHui
     * @param: [shoppingCart, id, dishId]
     * @return: void
     **/
    private void addDishToCar(ShoppingCart shoppingCart, Long id, String name, String image, BigDecimal price) {
        shoppingCart.setName(name);
        shoppingCart.setImage(image);
        shoppingCart.setUserId(id);
        shoppingCart.setNumber(1);
        shoppingCart.setAmount(price);
        shoppingCart.setCreateTime(LocalDateTime.now());
    }
    /**
     * 查询购物车
     *
     * @author: XieMingHui
     * @param: []
     * @return: com.sky.result.Result<java.util.List < com.sky.entity.ShoppingCart>>
     **/
    @Override
    public Result<List<ShoppingCart>> findCar() {
        Long id = UserThreadUtil.getThread().getId();
        log.info("当前用户id:{}", id);
        List<ShoppingCart> shoppingCartList = lambdaQuery().eq(ShoppingCart::getUserId, id)
                .list();
        if (shoppingCartList.size() == 0) {
            log.info("购物没有商品信息,返回空集合");
            return Result.success(Collections.emptyList());
        }
        return Result.success(shoppingCartList);
    }

    /**
     * 在购物车中删除商品
     *
     * @author: XieMingHui
     * @param: [shoppingCartDTO]
     * @return: com.sky.result.Result<java.lang.String>
     **/
    @Override
    public Result<String> subCar(ShoppingCartDTO shoppingCartDTO) {
        Long userId = UserThreadUtil.getThread().getId();
        Long dishId = shoppingCartDTO.getDishId(); // 菜品id
        Long setmealId = shoppingCartDTO.getSetmealId(); // 套餐id
        // 构建条件
        LambdaQueryChainWrapper<ShoppingCart> wrapper = lambdaQuery()
                .eq(ShoppingCart::getUserId, userId)
                .eq(dishId != null, ShoppingCart::getDishId, dishId)
                .eq(setmealId != null, ShoppingCart::getSetmealId, setmealId);
        // 判断菜品数量,如果大于1,修改数量-1
        ShoppingCart shoppingCart = wrapper.one();
        if (shoppingCart.getNumber()>1){
            boolean updateResult = lambdaUpdate().eq(ShoppingCart::getUserId, userId)
                    .eq(dishId != null, ShoppingCart::getDishId, dishId)
                    .eq(setmealId != null, ShoppingCart::getSetmealId, setmealId)
                    .setSql("number = number - 1").update();
            if (updateResult){
                return Result.success("修改成功");
            }
            return Result.success("修改失败");
        }
        // 判断菜品数量,如果为1,直接删除
        log.info("判断菜品数量,如果为1,直接删除");
        boolean remove = removeById(shoppingCart.getId());
        if (remove) {
            return Result.success("清空成功");
        }
        return Result.success("清空失败");
    }

    /**
     * 清空购物车
     *
     * @author: XieMingHui
     * @param: []
     * @return: com.sky.result.Result<java.lang.String>
     **/
    @Override
    @Transactional
    public Result<String> cleanCar() {
        Long userId = UserThreadUtil.getThread().getId();
        QueryWrapper<ShoppingCart> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(ShoppingCart::getUserId, userId);
        boolean remove = remove(wrapper);
        if (remove) {
            return Result.success("清空成功");
        }
        return Result.success("清空失败");
    }
}
